package com.cie2.janji.services;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Order;

import com.cie2.janji.entities.Article;

public class ArticleService {

	private Session session;
	
	public ArticleService(Session session) {
		this.session = session;
	}
	
	public void add(Article article) {
		session.persist(article);
		session.flush();
	}
	
	public Article load(Long articleId) {
		return (Article) session.load(Article.class,articleId);
	}
	
	public Article getLatestArticle() {				
		List list = session.createCriteria(Article.class)
			.addOrder(Order.desc("createdDate"))
			.setMaxResults(1) // always use in pair with fetch size for performance
			.setFetchSize(1)
			.list();
		
		if(list != null && list.size() > 0)
			return (Article) list.get(0);
		
		return new Article();

	}
	
	public List getAll() {
		return session.createCriteria(Article.class).list();
	}
	
	/**
	 * we start from the second item, because the first item will be fetch by latest article
	 * @return
	 */
	public List getMinorHeadline() {
		return session.createCriteria(Article.class)
			.addOrder(Order.desc("createdDate"))
			.setFirstResult(1)
			.setMaxResults(2) // always use in pair with fetch size for performance
			.setFetchSize(2)
			.list();
	}

}
